/**
 * 
 */
package com.asset.salesforce.controller.pages;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.asset.salesforce.domain.Appointment;
import com.asset.salesforce.domain.Calendar;
import com.asset.salesforce.domain.Call;
import com.asset.salesforce.domain.City;
import com.asset.salesforce.domain.Contact;
import com.asset.salesforce.domain.Country;
import com.asset.salesforce.domain.Employee;
import com.asset.salesforce.domain.Lead;
import com.asset.salesforce.domain.SharedLead;
import com.asset.salesforce.dto.LeadDTO;
import com.asset.salesforce.enums.LEADSTATUS;
import com.asset.salesforce.enums.PRIORITY;
import com.asset.salesforce.enums.RATING;
import com.asset.salesforce.enums.STATUS;
import com.asset.salesforce.service.AppointmentService;
import com.asset.salesforce.service.CalendarService;
import com.asset.salesforce.service.CallService;
import com.asset.salesforce.service.CityService;
import com.asset.salesforce.service.ContactService;
import com.asset.salesforce.service.CountryService;
import com.asset.salesforce.service.EmployeeService;
import com.asset.salesforce.service.LeadService;
import com.asset.salesforce.service.SharedLeadService;

// TODO: Auto-generated Javadoc
/**
 * The Class LeadController.
 *
 * @author Hisham
 */	
@Controller
public class LeadController {

	/** The lead service. */
	@Autowired
	private LeadService leadService;
	
	/** The employee service. */
	@Autowired
	private  EmployeeService employeeService;
	
	/** The country service. */
	@Autowired
	private CountryService countryService;
	
	/** The city service. */
	@Autowired
	private CityService cityService;
	
	/** The contact service. */
	@Autowired
	private ContactService contactService;
	
	/** The appointment service. */
	@Autowired
	private AppointmentService appointmentService;
	
	/** The call service. */
	@Autowired
	private CallService callService;
	
	/** The calendar service. */
	@Autowired
	private CalendarService calendarService;
	
	/** The sharedLeadService service. */
	@Autowired
	private SharedLeadService sharedLeadService;
	
	/**
	 * Gets the leads page.
	 *
	 * @param session the session
	 * @param model the model
	 * @param response the response
	 * @return the leads page
	 */
	@RequestMapping(value = "/leads", method = RequestMethod.GET)
	public String getLeadsPage(HttpSession session, Model model,HttpServletResponse response) {
		if (null == session.getAttribute("userDetails")) {return "redirect:login";}
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		List<Employee>employees = employeeService.getAllCompanyEmployess(userDetails.getCompany().getCompanyName());
		model.addAttribute("employees", employees);
		
		if(userDetails.getIsOwner()!=true){
			List<SharedLead>AllShared= sharedLeadService.getAllSharedByEmployee(userDetails.getId());
			List<Lead> sharedLeads = new ArrayList<Lead>();
			System.out.println("sharedLeads size>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+AllShared.size());
			
			if(AllShared.size()>0){
				for (SharedLead sharedLead : AllShared) {
					Lead lead = sharedLead.getLead();
					sharedLeads.add(lead);
				}
			}
			model.addAttribute("sharedLeads", sharedLeads);
		}
		
		LEADSTATUS[] leadStatus = LEADSTATUS.values();
		model.addAttribute("leadStatus", leadStatus);
		return "leadsPage";
	}
	
	/**
	 * Gets the new lead.
	 *
	 * @param session the session
	 * @param model the model
	 * @param response the response
	 * @param request the request
	 * @return the new lead
	 */
	@RequestMapping(value = "/newLead", method = RequestMethod.GET)
	public String getNewLead(HttpSession session, Model model,HttpServletResponse response,HttpServletRequest request){
		if (SecurityUtils.getSubject().hasRole("leadAdd")){
			try {
				request.setCharacterEncoding("UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			if(null ==session.getAttribute("userDetails") ){
				return "redirect:login";
			}
			Employee userDetails = (Employee)session.getAttribute("userDetails");
			RATING[] ratings = RATING.values();
			model.addAttribute("ratings", ratings);
			LEADSTATUS[] leadStatus = LEADSTATUS.values();
			model.addAttribute("leadStatus", leadStatus);
			model.addAttribute("userDetails",userDetails);
			List<Country> countries = countryService.getCountriesOrderById();
			model.addAttribute("countries",countries);
			model.addAttribute("leadDTO",new LeadDTO());
			return "createLeadPage";
			}
			else{
				return "accessDenied";
			}
		}
	
	/**
	 * Post new lead.
	 *
	 * @param session the session
	 * @param request the request
	 * @param response the response
	 * @param model the model
	 * @param leadForm the lead form
	 * @param result the result
	 * @return the string
	 */
	@RequestMapping(value="/newLead" ,method=RequestMethod.POST)
	public String postNewLead(HttpSession session,HttpServletRequest request,HttpServletResponse response,
			Model model,@Valid @ModelAttribute("leadDTO") LeadDTO leadForm,BindingResult result){
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:login";
		}	  		 
		Lead lead = new Lead();
		Contact contact =new Contact();
		Employee leadOwner = (Employee)session.getAttribute("userDetails");
				
		lead.setLeadOwner(leadOwner);
		contact.setCreator(leadOwner);
		contact.setViewType("lead");
		
		if(leadForm.getAnnualRevenue() != null){
			lead.setAnnualRevenue(leadForm.getAnnualRevenue());
		}
		
		if(leadForm.getCompanyName() != null && !leadForm.getCompanyName().equalsIgnoreCase("")){
			lead.setCompanyName(leadForm.getCompanyName());
		}
		
		if(leadForm.getCityDTO()!=null){
			City city = cityService.getById(leadForm.getCityDTO().getId());
			lead.setCity(city);
		}
		if(leadForm.getCountryDTO()!=null){
			Country country = countryService.getById(leadForm.getCountryDTO().getId());
			lead.setCountry(country);
		}
		if(leadForm.getDescription() != null && !leadForm.getDescription().equalsIgnoreCase("")){
			lead.setDescription(leadForm.getDescription());
		}
		if(leadForm.getEmail() != null && !leadForm.getEmail().equalsIgnoreCase("")){
			lead.setEmail(leadForm.getEmail());
			contact.setEmail(leadForm.getEmail());
		}
		if(leadForm.getNumOfEmp() != null){
			lead.setNumOfEmp(leadForm.getNumOfEmp());
		}
		if(leadForm.getfName() != null && !leadForm.getfName().equalsIgnoreCase("")){
			lead.setfName(leadForm.getfName());
			contact.setfName(leadForm.getfName());
		}
		if(leadForm.getIndustry() != null){
			lead.setIndustry(leadForm.getIndustry());
		}
		if(leadForm.getLeadSource()!= null&&!(leadForm.getLeadSource().equalsIgnoreCase(""))){
			lead.setLeadSource(leadForm.getLeadSource());
		}
		
		if(leadForm.getLeadStatus() != null){
            LEADSTATUS[] leadstatus = LEADSTATUS.values();
            lead.setLeadStatus(leadstatus[Integer.valueOf(leadForm.getLeadStatus())].getName());
		}

		if(leadForm.getlName() != null && !leadForm.getlName().equalsIgnoreCase("")){
			lead.setlName(leadForm.getlName());
			contact.setlName(leadForm.getlName());
		}
		
		if(leadForm.getPhone() != null && !leadForm.getPhone().equalsIgnoreCase("")){
			lead.setPhone(leadForm.getPhone());
			contact.setPhone(leadForm.getPhone());
		}
		
		if(leadForm.getMobile() != null && !leadForm.getMobile().equalsIgnoreCase("")){
			lead.setMobile(leadForm.getMobile());
			contact.setMobile(leadForm.getMobile());
		}
		
		if(leadForm.getRating() != null){
			RATING[] ratings = RATING.values();
			lead.setRating( ratings[Integer.valueOf(leadForm.getRating())].getName());
		}
		
		if(leadForm.getState() != null && !leadForm.getState().equalsIgnoreCase("")){
			lead.setState(leadForm.getState());
		}
		if(leadForm.getStreet() != null && !leadForm.getStreet().equalsIgnoreCase("")){
			lead.setStreet(leadForm.getStreet());
		}
		if(leadForm.getTitle() != null && !leadForm.getTitle().equalsIgnoreCase("")){
			lead.setTitle(leadForm.getTitle());
			contact.setTitle(leadForm.getTitle());
		}
		if(leadForm.getWebSite()!= null && !leadForm.getWebSite().equalsIgnoreCase("")){
			lead.setWebSite(leadForm.getWebSite());
		}
		if(leadForm.getZipCode() != null && !leadForm.getZipCode().equalsIgnoreCase("")){
			lead.setZipCode(leadForm.getZipCode());
		}
		if(leadForm.getInOutBound() != null && !leadForm.getInOutBound().equalsIgnoreCase("")){
			lead.setInOutBound(leadForm.getInOutBound().toString());
		}
		if(leadForm.getCarsNum() != null){
			lead.setCarsNum(leadForm.getCarsNum());
		}
		if(leadForm.getCategory() != null && !leadForm.getCategory().equalsIgnoreCase("")){
			lead.setCategory(leadForm.getCategory());
		}
		lead.setIsConverted(false);
		lead.setIsDeleted(false);
		contact.setIsDeleted(false);
		Date date = new Date();
		lead.setDateCreated(date);
		contact.setDateCreated(date);
		leadService.add(lead);
		contact.setParentName(lead.getfName());
		contact.setParentCompany(lead.getCompanyName());
		contact.setParentId(lead.getId());
		contact.setDateCreated(date);
		contact.setDateModified(date);
		contactService.add(contact);
		return  "redirect:leads";
	}

	/**
	 * Gets the edits the lead.
	 *
	 * @param session the session
	 * @param model the model
	 * @param request the request
	 * @param response the response
	 * @param id the id
	 * @return the edits the lead
	 */
	@RequestMapping(value="/editLead" ,method=RequestMethod.GET)
	public String getEditLead(HttpSession session,Model model,HttpServletRequest request,HttpServletResponse response
			,@RequestParam Integer id){
		if (SecurityUtils.getSubject().hasRole("leadEdit")){			
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:login";
		}
		model.addAttribute("id", id);
		RATING[] ratings = RATING.values();
	    model.addAttribute("ratings", ratings);
		LEADSTATUS[] leadStatus = LEADSTATUS.values();
		model.addAttribute("leadStatus", leadStatus);
		List<Country>countries = countryService.getAll();
		model.addAttribute("countries", countries);
		List<City> cities = new ArrayList<City>();
		Lead lead = leadService.getById(id);
		if(lead!=null){
			if(lead.getCountry() != null ){
				 cities = cityService.getAllCityByCountryId(lead.getCountry().getId());
			 }
		}
		 model.addAttribute("cities", cities);
		 model.addAttribute("leadDTO", lead);
		return "editLeadPage";
		}
		else{
			return "accessDenied";
		}
	}
	
	/**
	 * Post edit lead.
	 *
	 * @param session the session
	 * @param request the request
	 * @param response the response
	 * @param model the model
	 * @param leadForm the lead form
	 * @param result the result
	 * @return the string
	 */
	@RequestMapping(value="/editLead" ,method=RequestMethod.POST)
	public String postEditLead(HttpSession session,HttpServletRequest request,HttpServletResponse response,Model model,
			@Valid @ModelAttribute("leadDTO") Lead leadForm,BindingResult result){
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		
		Lead lead =leadService.getById(leadForm.getId());
		Employee leadOwner = (Employee)session.getAttribute("userDetails");
		lead.setLeadOwner(leadOwner);
		if(leadForm.getRating() != null&&!leadForm.getRating().equalsIgnoreCase("")){
			RATING[] ratings = RATING.values();
			lead.setRating(ratings[Integer.valueOf(leadForm.getRating())].getName());
		}
		if(leadForm.getIndustry() != null&&!leadForm.getIndustry().equalsIgnoreCase("")){
			lead.setIndustry(leadForm.getIndustry());
		}
		if(leadForm.getLeadStatus() != null&&!leadForm.getLeadStatus().equalsIgnoreCase("")){
			LEADSTATUS[] leadStatus = LEADSTATUS.values(); 
            lead.setLeadStatus(leadStatus[Integer.valueOf(leadForm.getLeadStatus())].getName());
		}
		if(leadForm.getLeadSource()!= null&&!(leadForm.getLeadSource().equalsIgnoreCase(""))){
			lead.setLeadSource(leadForm.getLeadSource());
		}
		if(leadForm.getCountry()!= null){
			Country country = countryService.getById(leadForm.getCountry().getId());
			lead.setCountry(country);
		}
		
		if(leadForm.getCity()!=null && !leadForm.getCity().getId().equals(0)){
			City city = cityService.getById(leadForm.getCity().getId());
			lead.setCity(city);
		}
		else{
			lead.setCity(null);
		}
		if(leadForm.getlName() != null && !leadForm.getlName().equalsIgnoreCase("")){
			lead.setlName(leadForm.getlName());
		}
		if(leadForm.getfName() != null && !leadForm.getfName().equalsIgnoreCase("")){
			lead.setfName(leadForm.getfName());
		}
		if(leadForm.getCompanyName() != null && !leadForm.getCompanyName().equalsIgnoreCase("")){
			lead.setCompanyName(leadForm.getCompanyName());
		}
		if(leadForm.getAnnualRevenue() != null){
			lead.setAnnualRevenue(leadForm.getAnnualRevenue());
		}
		if(leadForm.getNumOfEmp() != null){
			lead.setNumOfEmp(leadForm.getNumOfEmp());
		}
		if(leadForm.getDescription() != null && !leadForm.getDescription().equalsIgnoreCase("")){
			lead.setDescription(leadForm.getDescription());
		}
		if(leadForm.getWebSite()!= null && !leadForm.getWebSite().equalsIgnoreCase("")){
			lead.setWebSite(leadForm.getWebSite());
		}
		if(leadForm.getPhone() != null && !leadForm.getPhone().equalsIgnoreCase("")){
			lead.setPhone(leadForm.getPhone());
		}
		if(leadForm.getMobile() != null && !leadForm.getMobile().equalsIgnoreCase("")){
			lead.setMobile(leadForm.getMobile());
		}
		if(leadForm.getTitle() != null && !leadForm.getTitle().equalsIgnoreCase("")){
			lead.setTitle(leadForm.getTitle());
		}
		if(leadForm.getEmail() != null && !leadForm.getEmail().equalsIgnoreCase("")){
			lead.setEmail(leadForm.getEmail());
		}
		if(leadForm.getZipCode() != null && !leadForm.getZipCode().equalsIgnoreCase("")){
			lead.setZipCode(leadForm.getZipCode());
		}
		if(leadForm.getState() != null && !leadForm.getState().equalsIgnoreCase("")){
			lead.setState(leadForm.getState());
		}
		if(leadForm.getStreet() != null && !leadForm.getStreet().equalsIgnoreCase("")){
			lead.setStreet(leadForm.getStreet());
		}
		if(leadForm.getInOutBound() != null && !leadForm.getInOutBound().equalsIgnoreCase("")){
			lead.setInOutBound(leadForm.getInOutBound().toString());
		}
		if(leadForm.getCarsNum() != null){
			lead.setCarsNum(leadForm.getCarsNum());
		}
		if(leadForm.getCategory() != null && !leadForm.getCategory().equalsIgnoreCase("")){
			lead.setCategory(leadForm.getCategory());
		}
		lead.setIsDeleted(false);
		lead.setIsConverted(false);
		lead.setDateModified(new Date());
		leadService.saveOrUpdate(lead);		
		return "redirect:leads";
	}
	
	/**
	 * Gets the view lead.
	 *
	 * @param session the session
	 * @param model the model
	 * @param request the request
	 * @param response the response
	 * @param id the id
	 * @return the view lead
	 */
	@RequestMapping(value="/viewLead" ,method=RequestMethod.GET)
	public String getViewLead(HttpSession session,Model model,HttpServletRequest request,HttpServletResponse response,@RequestParam Integer id){
		if (SecurityUtils.getSubject().hasRole("leadView")){			
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:login";
		}
		Lead lead = leadService.getById(id);
		model.addAttribute("leadDTO", lead);
		List<Appointment>appointments = appointmentService.getAppointmentByParentId(id, "lead");
		model.addAttribute("appointments",appointments);
		List<Call>calls = callService.getCallByParentId(id, "lead");
		model.addAttribute("calls",calls);
		return "viewLeadPage";
		}
		else{
			return "accessDenied";
		}
	}

	/**
	 * Transfer lead.
	 *
	 * @param session the session
	 * @param model the model
	 * @param request the request
	 * @param response the response
	 * @param leadId the lead id
	 * @param empId the emp id
	 * @return the string
	 */
	@RequestMapping(value = "/transferLead", method = RequestMethod.GET)
	public String transferLead(HttpSession session,Model model,HttpServletRequest request,HttpServletResponse response,@RequestParam Integer[] leadId,Integer empId){
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}			
		 Employee leadOwner = employeeService.getById(empId);
		 for(Integer id:leadId){
			 Lead lead = leadService.getById(id);
			 lead.setLeadOwner(leadOwner);
			 lead.setDateModified(new Date());
			 leadService.saveOrUpdate(lead);
			 List<Contact>contacts = contactService.getContactsByParentType(lead.getId(), "lead");
			 if(contacts!=null){
				 for (Contact contact : contacts) {
					 contact.setCreator(leadOwner);
					 contact.setDateModified(new Date());
					 contactService.saveOrupdate(contact);
				}
			 }
			 
			 List<Call>calls = callService.getCallByParentId(id, "lead");
			 if(calls.size()>0){
				 for (Call call : calls) {
						List<Calendar>calendars = calendarService.getAllCallEvents(call.getId());
						if(calendars.size()>0){
							for (Calendar calendar : calendars) {
								calendar.setEmpId(leadOwner);
								calendarService.saveOrupdate(calendar);
							}
						}
					} 
			 }
			List<Appointment>appointments = appointmentService.getAppointmentByParentId(id,"lead");
			if(appointments.size()>0){
				for (Appointment appointment : appointments) {
					List<Calendar>calendars = calendarService.getAllAppointmentEvents(appointment.getId());
					if(calendars.size()>0){
						for (Calendar calendar : calendars) {
							calendar.setEmpId(leadOwner);
							calendarService.saveOrupdate(calendar);
						}
					}
				}
			}			
		 }
		 return "redirect:leads";	
	}
	
	/**
	 * Share lead.
	 *
	 * @param session the session
	 * @param model the model
	 * @param request the request
	 * @param response the response
	 * @param leadId the lead id
	 * @param empId the emp id
	 * @return the leads page
	 */
	@RequestMapping(value = "/shareLead", method = RequestMethod.GET)
	public String shareLead(HttpSession session,Model model,HttpServletRequest request,HttpServletResponse response,@RequestParam Integer[] leadId,Integer empId){
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}			
		 Employee leadOwner = employeeService.getById(empId);
		 for(Integer id:leadId){
			 SharedLead sharedLead = new SharedLead();
			 Lead lead = leadService.getById(id);
			 sharedLead.setLead(lead);
			 sharedLead.setEmployee(leadOwner);
			 sharedLeadService.add(sharedLead);
		 }
		 return "redirect:leads";	
	}
	
	@RequestMapping(value="/convertLead" ,method=RequestMethod.GET)
	public String getConvertLeadPage(Model model ,HttpSession session ,HttpServletRequest request ,HttpServletResponse response){
		if (SecurityUtils.getSubject().hasRole("leadConvert")){		
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:login";
		}
		
		Integer id = Integer.parseInt(request.getParameter("id").toString());
		Lead lead = leadService.getById(id);
		model.addAttribute("leadDTO", lead);
		LEADSTATUS[] leadStatus = LEADSTATUS.values();
		model.addAttribute("leadStatus", leadStatus);
		STATUS[] status = STATUS.values();
		model.addAttribute("status", status);
		PRIORITY[] priorities = PRIORITY.values();
		model.addAttribute("priorities", priorities );
		
		return "convertLeadPage";
		}
		else{
			return "accessDenied";
		}
	}
}
